import React from 'react';
import { Modal, Checkbox, Spin } from 'antd';
import { userTypeList } from '@/services/geographic';

class UserTypeModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      loading: false,
      list: [],
      checkedValues: [],
      disabledValues: []
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  openModal = (welcomeList) => {
    //将已选择的机器人作选中状态 且不能修改
    const checkedValues = welcomeList.map(item => item.userTypeId);
    this.setState({ visible: true, checkedValues, disabledValues: checkedValues }, () => {
      this.getUserTypeList();
    })
  }

  getUserTypeList = () => {
    this.setState({ loading: true }, async () => {
      const res = await userTypeList({ current: 1, size: 999999 });
      this.setState({
        list: res.records ? res.records : [],
        loading: false,
      })
    })
  }

  onChangeCheck = (checkedValues) => {
    this.setState({ checkedValues })
  }

  cancelModal = () => {
    this.setState({ visible: false })
  }

  addPersonal = () => {
    const { list, checkedValues, disabledValues } = this.state;
    const arr = [];
    for (const item of list) {
      //1.checkedValues 当前选中的用户类型（包括之前已经选中的数据）
      //2.disabledValues 之前选中的数据
      //3.新增选中的且之前没有选过的数据
      if (checkedValues.indexOf(item.id) > -1 && disabledValues.indexOf(item.id) === -1) {
        let obj = {
          id: '',
          userTypeId: item.id,
          userTypeName: item.tagName,
          // userTypeCode: item.userTypeCode,
          welcomeType: 1,
          welcomeContent: '您好，请问有什么可以帮助您？',
          questionList: [],
          welcomeInput: '',
          welcomeEditor: '您好，请问有什么可以帮助您？'
        }
        arr.push(obj)
      }
    }
    this.props.addPersonalWelcome(arr)
    this.cancelModal();
  }

  render() {
    const { visible, loading, list, checkedValues, disabledValues } = this.state;

    return (
      <Modal title={'添加个性化欢迎语'} visible={visible} onCancel={this.cancelModal} onOk={this.addPersonal}>
        <Spin spinning={loading}>
          <div style={{ marginBottom: 20 }}>请选择要添加个性化欢迎语的用户类型：</div>
          <Checkbox.Group style={{ width: '100%' }} onChange={this.onChangeCheck} value={checkedValues}>
            {
              list.map((item, index) => {
                return (
                  <Checkbox value={item.id} key={item.id} disabled={disabledValues.indexOf(item.id) > -1} style={{ marginBottom: 10 }}>
                    {item.tagName}{disabledValues.indexOf(item.id) > -1 ? '(已添加)' : ''}
                  </Checkbox>
                )
              })
            }
          </Checkbox.Group>
        </Spin>
      </Modal>
    );
  }
}

export default UserTypeModal;
